package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.YddArticleDto;
import com.itheima.ydd.entity.YddArticle;
import com.itheima.ydd.entity.YddCate;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.entity.YddUserData;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IYddUserService yddUserService;

    @Autowired
    private IYddUserDataService yddUserDataService;

    @Autowired
    private IYddArticleService yddArticleService;

    @Autowired
    private IYddCateService yddCateService;


    /**
     * 获取用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("/getUserInfo")
    public ResultData getuserInfo(HttpServletRequest request) {

        Map<String, Object> data = new HashMap<>();
        //从token中获取用户信息
        String token = request.getHeader("token");
        Claims claims = JwtUtils.getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        System.out.println("userId = " + userId);

        YddUser user = yddUserService.getById(userId);
        user.setPassword("");

        data.put("userInfo", user);

        //获取用户发布的文章数
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddArticle::getUserId, userId);
        int articleNum = yddArticleService.count(wrapper);
        data.put("articleNum", articleNum);

        //获取用户点赞的文章数
        LambdaQueryWrapper<YddUserData> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(YddUserData::getUserId, userId);
        wrapper1.eq(YddUserData::getType, 2);
        int zanNum = yddUserDataService.count(wrapper1);
        data.put("zanNum", zanNum);

        //获取用户收藏的文章数
        LambdaQueryWrapper<YddUserData> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(YddUserData::getUserId, userId);
        wrapper2.eq(YddUserData::getType, 1);
        int collectNum = yddUserDataService.count(wrapper2);
        data.put("collectNum", collectNum);

        return ResultData.ok("",data);

    }

    /**
     * 修改个人资料
     * @param yddUser
     * @return
     */
    @PostMapping("/update")
    public R update(@RequestBody YddUser yddUser){

        if(StringUtils.isNotEmpty(yddUser.getPassword())){
            String password = DigestUtils.md5DigestAsHex(yddUser.getPassword().getBytes());
            yddUser.setPassword(password);
        }else {
            YddUser user = yddUserService.getById(yddUser.getId());
            yddUser.setPassword(user.getPassword());
        }

        yddUserService.updateById(yddUser);
        return R.success("");

    }

    /**
     * 获取收藏和点赞文章列表
     *
     * @param page
     * @param limit
     * @param type
     * @param request
     * @return
     */
    @GetMapping("/userDataList")
    public R getDataList(int page, int limit, int type, HttpServletRequest request) {

        //从token中获取用户信息
        String token = request.getHeader("token");
        Claims claims = JwtUtils.getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        System.out.println("userId = " + userId);


        Page<YddUserData> pageInfo = new Page<>(page, limit);
        LambdaQueryWrapper<YddUserData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddUserData::getUserId, userId);
        wrapper.eq(YddUserData::getType, type);
        wrapper.orderByDesc(YddUserData::getId);
        yddUserDataService.page(pageInfo, wrapper);
        List<YddUserData> userDataList = pageInfo.getRecords();
        System.out.println("userDataList = " + userDataList);

        List<YddArticle> articles = new ArrayList<>();

        for (YddUserData yddUserData : userDataList) {
            Integer articleId = yddUserData.getArticleId();
            YddArticle article = yddArticleService.getById(articleId);
            if (article != null) {
                articles.add(article);
            }
        }

        List<YddArticleDto> dataList = articles.stream().map(item -> {
            YddArticleDto yddArticleDto = new YddArticleDto();
            BeanUtils.copyProperties(item, yddArticleDto);

            LambdaQueryWrapper<YddCate> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(YddCate::getId, item.getCateid());
            YddCate yddCate = yddCateService.getOne(wrapper1);

            yddArticleDto.setCatename(yddCate.getCatename());
            return yddArticleDto;
        }).collect(Collectors.toList());


        Map<String, Object> data = new HashMap<>();
        Map<String, Object> list = new HashMap<>();
        list.put("data", dataList);
        list.put("count", pageInfo.getTotal());
        list.put("totalPages", pageInfo.getPages());
        list.put("currentPage", pageInfo.getCurrent());
        list.put("pageSize", pageInfo.getSize());

        data.put("list", list);

        return R.success("",data);

    }


    /**
     * 获取我的文章
     *
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping("/myArticle")
    public R getMyArticle(int page, int limit, HttpServletRequest request) {

        //从token中获取用户信息
        String token = request.getHeader("token");
        Claims claims = JwtUtils.getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        System.out.println("userId = " + userId);


        Page<YddArticle> pageInfo = new Page<>(page, limit);
        LambdaQueryWrapper<YddArticle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddArticle::getUserId, userId);
        wrapper.orderByDesc(YddArticle::getCreateDate);
        yddArticleService.page(pageInfo, wrapper);

        PageResult pageResult = PageResult.getResult(pageInfo);

        return R.success("",pageResult);

    }


    /**
     * 修改文章
     *
     * @return
     */
    @PostMapping("/editArticle")
    public R editArticle(@RequestBody YddArticle yddArticle, HttpServletRequest request) {

        //从token中获取用户信息
        String token = request.getHeader("token");
        Claims claims = JwtUtils.getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        System.out.println("userId = " + userId);


        yddArticle.setUpdateDate(System.currentTimeMillis());
        yddArticle.setUserId(userId);

        yddArticleService.updateById(yddArticle);
        return R.success("修改成功");

    }

    /**
     * 发布文章
     *
     * @return
     */
    @PostMapping("/addArticle")
    public R addArticle(@RequestBody YddArticle yddArticle, HttpServletRequest request) {

        //从token中获取用户信息
        String token = request.getHeader("token");
        Claims claims = JwtUtils.getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        System.out.println("userId = " + userId);

        yddArticle.setCreateDate(System.currentTimeMillis());
        yddArticle.setUpdateDate(System.currentTimeMillis());
        yddArticle.setUserId(userId);

        yddArticleService.save(yddArticle);
        return R.success("");

    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @GetMapping("/delArticle")
    public R deleteArticle(String id) {

        yddArticleService.removeById(id);

        LambdaQueryWrapper<YddUserData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddUserData::getArticleId, id);
        yddUserDataService.remove(wrapper);

        return R.success("");

    }


    /**
     * 点赞/取消点赞和收藏/取消收藏
     * @param type
     * @param action
     * @param articleId
     * @return
     */
    @GetMapping("/userDataHandle")
    public R userDataHandle(Integer type, String action, @RequestParam("article_id") Integer articleId , HttpServletRequest request) {

        //从token中获取用户信息
        String token = request.getHeader("token");
        Claims claims = JwtUtils.getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        System.out.println("userId = " + userId);

        //add表示点赞或收藏，del表示取消点赞或取消收藏
        if (StringUtils.isNotEmpty(action) && "del".equals(action)) {

            LambdaQueryWrapper<YddUserData> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(articleId != null, YddUserData::getArticleId, articleId);
            wrapper.eq(type != null, YddUserData::getType, type);
            wrapper.eq(YddUserData::getUserId, userId);
            yddUserDataService.remove(wrapper);
            return R.success("");

        } else if (StringUtils.isNotEmpty(action) && "add".equals(action)) {

            YddUserData userData = new YddUserData();
            userData.setArticleId(articleId);
            userData.setUserId(userId);
            userData.setType(type);
            yddUserDataService.save(userData);

            return R.success("");


        }

        return R.error("暂时无法进行操作!");

    }

}
